/*
 * Vlabs Biological Web Elemments
 *
 * Copyright (c) 2009 Victor de la Torre (vdelatorre@cnio.es)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 * 
 * http://code.google.com/p/bwe/ 
 *
 */
 var map,layers,popup,bp,chr,options;
 var das_server	= '';
 var pid 		= '';
 var dsn 		= '';
 var segment 	= ''
 var size		= 0;
 var baseUrl 	= 'http://madas2.bioinfo.cnio.es/plugins_dir/visualization/madasmap/';
/*   var baseUrl 	= 'http://localhost/madas/plugins_dir/visualization/madasmap/'; */
  
 (function($) {
 
    $.bwe.madasmap = $.bwe.madasmap || {}; //Add the 'madasmap' scope
    
    
	$.bwe.madasmap.instance = function(container,label,iwidth,iheight,open){

		$.bwe.madasmap.buidMapElement(container,label,iwidth,iheight,'$.bwe.madasmap.buildMap','MaDASmap',open);
	}
	
	
	$.bwe.madasmap.buidMapElement = function(container,label,iwidth,iheight,elementOnClick,elementLabel,open){
	
		var id	 		= Math.floor(Math.random()*1000);
		var mapWidth	= iwidth-180;
	
		
		element = jQuery('<div style="display:inline;"><table style="display:inline" cellspacing="0"><tr><td class="bwe-label" style="color:#E80307"><b>'+label+'</b> <span class="parentesis">{</span><a id="trigger_'+id+'" href="#">'+elementLabel+'</a><span class="parentesis">}</span></td></tr><tr><td><div id="'+id+'" class="bwe-content bwe-hidden" valign="top" align="center" style="overflow:auto;"><div id="bubble" style="background:url(\'http://ubio.bioinfo.cnio.es/biotools/bwe/images/bubbleg.png\') no-repeat; width:300px; height:400px; display:none; position:absolute; z-index:10000"></div><div id="bubbler" style="background:url(\'http://ubio.bioinfo.cnio.es/biotools/bwe/images/bubblegr.png\') no-repeat; width:300px; height:400px; display:none;position:absolute; z-index:10000"></div><table cellpadding="0" cellspacing="0"><tr><td><div id="map" class="smallmap" style="text-align:left;width:'+mapWidth+'px;height:'+iheight+'px;background-color:#FFFFFF;"></div></td><td valign="top"><div id="'+id+'_tbar" class="tbar"></div></td></tr></table><div id="resolution"></div></div></td></tr></table></div>');

		container.append(element);
		
		
		$('#trigger_'+id).bind('click',function(e){
			$.bwe.madasmap.buildMap(id,iwidth,iheight);
			$.bwe.madasmap.getTypes(id);
		});

		if (open){
			$('#trigger_'+id).trigger('click');
		}
		
	}
	
	$.bwe.madasmap.mapMouseDown = function(e){
	    
	    map.lastMouseX = e.xy.x;
	    map.lastMouseY = e.xy.y;
	    
	    $("#bubble").hide();
		$("#bubble").empty();
		$("#bubbler").hide();
		$("#bubbler").empty();
	 }
	
	 $.bwe.madasmap.mapMouseUp = function(e){

	    var tx = e.xy.x;
	    var ty = e.xy.y;
	    var tot = Math.abs(map.lastMouseX - tx)+ Math.abs(map.lastMouseY - ty);
	    if(2 > tot){
	    	// dont need to figure out basepairs from pixels
	        // just use the ones in the window already.
	        $.bwe.madasmap.getFeature(tx,ty,parseInt(bp.element.innerHTML));
	    }
	 }
	
	$.bwe.madasmap.buildMap = function(id,iwidth,iheight){
		
        if ($.bwe.animate(id,iwidth,iheight)){
	        
	        var chr 	= segment;
	        var version = 1;
			var server = baseUrl+'wms.php?iwidth='+iwidth+'&iheight='+iheight+'&das_server='+das_server+'&project='+pid+'&dsn='+dsn+'&segment='+segment+'&size='+size;
	        var org = "";
	
	        var ds	 	= 588;
	        var loc 	= size/2;
	        var zoom 	= 0;
	
		    //base WMS layer
		    options = {   
	                 maxExtent: new OpenLayers.Bounds(0,-10000,size,10000),
	                 units     :'bp',
	                 tileSize: new OpenLayers.Size(200, iheight),
	                 resolutions: [size/872,size/1744,size/3488,size/6976,size/13952,size/27904,size/55808,size/111616,size/223232,size/446464,size/892928,size/1785856],
	                 controls: [new OpenLayers.Control.MouseDefaults()]
	            };
	            
	    	map = new OpenLayers.GenomeBrowser('map',options);
	
			/* Layers */
			layer = new OpenLayers.Layer.Genomic( "<span id='gene'>Genes</span>" , server
	             ,{'ds': ds, 'chr':chr,layers:"gene",'version':version,organism:org}
	             ,{isBaseLayer:true})	        
	   	    
	   	    map.addLayer(layer);
	    	
	    	/* Zoom and center */
	    	map.setCenter(new OpenLayers.BasePair(loc), zoom);
	    	
	    	/* Controls */   	
	        bp = new OpenLayers.Control.MousePosition() 
	    	map.addControl(bp );
	        map.addControl(new OpenLayers.Control.PanZoomBar());
	        
	        /* Events */
		    map.events.register('mousedown',map,$.bwe.madasmap.mapMouseDown);
		    map.events.register('mouseup',map,$.bwe.madasmap.mapMouseUp);
		}
	}
	
	$.bwe.madasmap.getTypes = function(id){
		
		var proxy	= 'http://bwsp.bioinfo.cnio.es/bwsp.php?bwsp_force_no_cache=1&bwsp_service=madas&bwsp_response_format=json&bwsp_url=';
		var server 	= proxy+baseUrl+'types.php?das_server='+das_server+',project='+pid+',dsn='+dsn+',segment='+segment+'&bwsp_callback=?';

		jQuery.getJSON(server,function(data){
			
			$('#'+id+'_tbar').append('<div style="height:20px;padding-left:10px;"><b>Features</b></div>');
			$('#'+id+'_tbar').append('<div style="height:26px;width:100px;border:1px solid #FFFFFF;font-family:arial;font-size:9px;padding-left:10px;">Sequence</div>');
			
			$.each(data.types.type,function(i,item) {
				f = jQuery('<div style="height:18px;width:150px;border:1px solid #FFFFFF;font-family:arial;font-size:10px;padding-left:10px;">'+item+'</div>');
				$('#'+id+'_tbar').append(f);
				
			});
		})
	}
	
	
	$.bwe.madasmap.getFeature = function(tx,ty,sstart){

	  var sstop	= 0;
	  var h		= ty;
	  var proxy	= 'http://bwsp.bioinfo.cnio.es/bwsp.php?bwsp_force_no_cache=1&bwsp_service=madas_features&bwsp_response_format=json&bwsp_url=';
	  
	  if (parseFloat(map.getResolution()) >1){
	  	sstart 	= parseInt(sstart)-3*parseInt(map.getResolution());
	   	sstop 	= parseInt(sstart)+3*parseInt(map.getResolution());
	  }else{
	  	sstart 	= parseInt(sstart);
	  	sstop	= sstart+1;
	  }
	  
	  var server 	= proxy+baseUrl+'features.php?das_server='+das_server+',project='+pid+',dsn='+dsn+',segment='+segment+',size='+size+',start='+sstart+',stop='+sstop+',h='+h+'&bwsp_callback=?';
	  jQuery.getJSON(server,function(data){
	  
		if (data){	
			if (ty >= 350){
				$.bwe.madasmap.paintFeature($('#bubble'),data,0);
				$("#bubble").css({
				  left:tx+$('#map').offset().left-68,
				  top:$('#map').offset().top+ty-$("#bubble").height()
				}).show();
			
			}else{
				$.bwe.madasmap.paintFeature($('#bubbler'),data,1 );
				$("#bubbler").css({
					left:tx+$('#map').offset().left-68,
					top:$('#map').offset().top+ty
				}).show();
			}
			$(".scroll-pane").jScrollPane({scrollbarWidth:5, scrollbarMargin:1, showArrows:false});
		}  
	  });
	}
	
	$.bwe.madasmap.paintFeature = function(fc,data,r){
		
		if (r)
			fc.append('<div style="margin-top:40px;">&nbsp;</div>');
		else
			fc.append('<div style="margin-top:12px;">&nbsp;</div>');
				
		scroll = jQuery('<div class="scroll-pane fdetails"></div>');
		
		/* single feature */
		if (data.features.feature.id){
			scroll.append(jQuery('<div class="field"><b>ID</b>: '+data.features.feature.id+'</div>'));
			if (data.features.feature.type)
				scroll.append(jQuery('<div class="field"><b>Type:</b> '+data.features.feature.type+'</div>'));
			if (data.features.feature.start)
				scroll.append(jQuery('<div class="field"><b>Start:</b> '+data.features.feature.start+'</div>'));
			if (data.features.feature.stop)
				scroll.append(jQuery('<div class="field"><b>Stop:</b> '+data.features.feature.stop+'</div>'));
			if (data.features.feature.score && data.features.feature.score != ',')
				scroll.append(jQuery('<div class="field"><b>Score:</b> '+data.features.feature.score+'</div>'));
			if (data.features.feature.phase)
				scroll.append(jQuery('<div class="field"><b>Phase:</b> '+data.features.feature.phase+'</div>'));
			if (data.features.feature.link != '<a href="" target="_blank"></a>')
				scroll.append(jQuery('<div class="field">'+data.features.feature.link+'</div>'));
			if (data.features.feature.notes)
				$.bwe.madasmap.paintNotes(scroll,data.features.feature.notes);		
		//mutiple
		}else{
			$.each(data.features.feature,function(i,item) {	
				if (item.id)
					scroll.append(jQuery('<div class="field"><b>ID:</b> '+item.id+'</div>'));
				if (item.type)
					scroll.append(jQuery('<div class="field"><b>Type:</b> '+item.type+'</div>'));
				if (item.start)
					scroll.append(jQuery('<div class="field"><b>Start:</b> '+item.start+'</div>'));
				if (item.stop)
					scroll.append(jQuery('<div class="field"><b>Stop:</b> '+item.stop+'</div>'));
				if (item.score && item.score != ',')
					scroll.append(jQuery('<div class="field"><b>Score:</b> '+item.score+'</div>'));
				if (item.phase)
					scroll.append(jQuery('<div class="field"><b>Phase:</b> '+item.phase+'</div>'));
				if (item.link != '<a href="" target="_blank"></a>')
					scroll.append(jQuery('<div class="field">'+item.link+'</div>'));
				scroll.append(jQuery('<div style="height:10px;">&nbsp;</div>'));
	
			});
		}
		
		fc.append(scroll);	
	}
	
	$.bwe.madasmap.paintNotes = function(fc,notes){
		
		fc.append(jQuery('<div class="notes">Other Information</div>'));
		/* single */
		if (notes.note.constructor.toString().indexOf("Array") == -1){
			fc.append(jQuery('<div class="field">'+notes.note+'</div>'));
		/* multiple */
		}else{
			$.each(notes.note,function(i,item) {
				if (item.match('CLUSTER')){
					var clusterName = item.replace(/CLUSTER:/,'');
					var link = 'CLUSTER: <a href="#" onclick="$.bwe.madasmap.triggerFragKb(\''+clusterName+'\')">'+clusterName+'</a>';
					fc.append(jQuery('<div class="field">'+link+'</div>'));
				}else{
					fc.append(jQuery('<div class="field">'+item+'</div>'));
				}
			});
		}
	}
	
	$.bwe.madasmap.triggerFragKb = function(clusterName){
		
		$("#bubble").hide();
		$("#bubble").empty();
		$("#bubbler").hide();
		$("#bubbler").empty();
		$('#fragkb').empty();
		$.bwe.fragkb.instance($('#fragkb'),clusterName,'getClusterInfo','FragKB Cluster Information',true);
	}
	

 })(jQuery);	